package com.jokerx.ohos.fasttrpg.gamemaster;

import com.jokerx.ohos.fasttrpg.ResourceTable;
import com.jokerx.ohos.fasttrpg.entity.RoleInfo;
import com.jokerx.ohos.fasttrpg.play.PlayConstant;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.LocalRemoteObject;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.global.resource.Resource;
import ohos.rpc.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameMasterServiceAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.DEBUG, 0xD001100, GameMasterServiceAbility.class.getName());

    private GameMasterServiceRemoteObject gameMasterServiceRemoteObject;

    private List<RoleInfo> playerRoleInfos;

    @Override
    public void onStart(Intent intent) {
        HiLog.error(LABEL_LOG, "GameMasterServiceAbility::onStart");
        super.onStart(intent);
        gameMasterServiceRemoteObject = new GameMasterServiceRemoteObject();
        playerRoleInfos = new ArrayList<>();
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(LABEL_LOG, "GameMasterServiceAbility::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.info(LABEL_LOG, "GameMasterServiceAbility::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        super.onConnect(intent);
        return gameMasterServiceRemoteObject.asObject();
    }

    @Override
    public void onDisconnect(Intent intent) {
    }

    /**
     * GameMasterRemoteObject
     *
     * @author liangxu14
     * @date 2022/5/5
     */
    private class GameMasterServiceRemoteObject extends RemoteObject implements IRemoteBroker {

        public GameMasterServiceRemoteObject() {
            super("GameMasterService_Remote");
        }

        @Override
        public IRemoteObject asObject() {
            return this;
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            String token = data.readInterfaceToken();
            if (!GameMasterServiceConstant.DESCRIPTOR.equals(token)) {
                reply.writeInt(GameMasterServiceConstant.ERROR);
                return false;
            }

            if (code != GameMasterServiceConstant.COMMAND_SELECT_ROLE) {
                reply.writeInt(GameMasterServiceConstant.ERROR);
                return false;
            }

            switch (code){
                case GameMasterServiceConstant.COMMAND_SELECT_ROLE:
                    reply.writeInt(GameMasterServiceConstant.ERR_OK);
                    selectRole(data.readString(), data.readInt());
                    return true;
                case GameMasterServiceConstant.COMMAND_START_GAME:
                    reply.writeInt(GameMasterServiceConstant.ERR_OK);
                    startGame();
                    return true;
                default:
                    reply.writeInt(GameMasterServiceConstant.ERROR);
                    return false;
            }
        }

        private void selectRole(String playerId, int roleId) {
            playerRoleInfos.add(new RoleInfo(playerId, roleId));
        }

        private void startGame() {
            TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            playerRoleInfos.forEach(roleInfo -> globalTaskDispatcher.asyncDispatch(() -> startPlayerGame(roleInfo.getPlayerId(), roleInfo.getRoleId())));
        }

        private void startPlayerGame(String deviceId, int roleId) {
            // 指定待启动FA/PA的bundleName和abilityName
            // 设置分布式标记，表明当前涉及分布式能力
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId(deviceId)
                    .withBundleName(getBundleName())
                    .withAbilityName("com.jokerx.ohos.fasttrpg.play.PlayAbility")
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .withAction("ability.intent.PLAY_GAME")
                    .build();
            intent.setOperation(operation);
            // 设置传递参数
            IntentParams intentParams = new IntentParams();
            intentParams.setParam(PlayConstant.SCENE_IMG_SRC, ResourceTable.Media_scene_01);
            intentParams.setParam(PlayConstant.ROLE_LIST, playerRoleInfos);
            intent.setParam(PlayConstant.PLAY_ABILITY_SLICE_PARAM, intentParams);
            intent.setParam("masterDeviceId", getOriginalDeviceId());
            // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
            startAbility(intent);
        }

        private void roll(String deviceId, int score) {

        }
    }
}